<template>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="公司名称">
        <el-input v-model="formInline.name" placeholder="公司名称" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getList">搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="listData" height="650" style="width: 100%">
      <el-table-column prop="id" label="终端号" />
      <el-table-column prop="SN" label="SN号" />
      <el-table-column prop="startTime" label="服务开始时间" />
      <el-table-column prop="endTime" label="服务结束时间" />
      <el-table-column prop="name" label="公司名称" />
      <el-table-column prop="state" label="设备状态">
        <template #default="{ row }">
          <span>
            {{ row.state === 1 ? "使用中" : "已禁用" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240px">
        <template #default="{ row }">
          <el-button @click="openDialog(row)">详情</el-button>
          <el-button @click="openEditDialog(row)">编辑</el-button>
          <el-button type="danger">禁用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 对话框  -->
    <Dialog
      v-model="dialogFormVisible"
      :rowData="currentRow"
      @save="handleSave"
    ></Dialog>
  </div>
</template>

<script  setup>
import axios from "axios";
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import Dialog from "../../components/Dialog.vue";
const dialogFormVisible = ref(false);
const listData = ref([]);
const currentRow = ref(null);

const formInline = reactive({
  name: "",
});

// 打开编辑对话框
const openEditDialog = (row) => {
  currentRow.value = { ...row }; // 创建副本防止污染原始数据
  dialogFormVisible.value = true;
};

// 编辑保存处理
const handleSave = async (updatedData) => {
  const res = await axios.put(
    `http://localhost:1243/data/${updatedData.id}`,
    updatedData
  );
  console.log(res);

  ElMessage({
    message: "编辑成功",
    type: "success",
  });
  getList()
};

//打开对话框
const openDialog = (row) => {
  currentRow.value = row;
  dialogFormVisible.value = true;
};

//请求列表数据
const getList = async () => {
  const res = await axios.get("http://localhost:1243/data", {
    params: { ...formInline },
  });
  console.log(res);

  listData.value = res.data;
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
</style>